<?php

declare(strict_types=1);

namespace app\validate\notify;

use think\Validate;

class MessageValidate extends Validate
{
    protected $rule = [
        'template_type' => 'max:80',
        'template_id' => 'integer|gt:0',
        'title' => 'max:255',
        'content' => 'max:65535',
        'data' => 'checkAssoc',
        'payload' => 'checkAssoc',
        'route' => 'max:255',
        'recipients' => 'require|checkRecipients',
    ];

    protected $message = [
        'template_type.max' => '模板类型不能超过80个字符',
        'template_id.integer' => '模板ID必须为整数',
        'template_id.gt' => '模板ID必须大于0',
        'title.max' => '标题长度不能超过255个字符',
        'content.max' => '内容长度超出限制',
        'route.max' => '路由长度不能超过255个字符',
        'recipients.require' => '接收者不能为空',
    ];

    protected $scene = [
        'create' => [
            'template_type',
            'template_id',
            'title',
            'content',
            'data',
            'payload',
            'route',
            'recipients',
        ],
    ];

    protected function checkRecipients($value)
    {
        if (!is_array($value) || $value === []) {
            return '接收者不能为空';
        }

        foreach ($value as $item) {
            if (!is_array($item)) {
                return '接收者格式不正确';
            }

            $id = $item['target_id'] ?? $item['id'] ?? null;
            $type = $item['target_type'] ?? $item['type'] ?? null;

            if ($id === null || $type === null || trim((string) $type) === '') {
                return '接收者信息不完整';
            }

            if (is_string($id) && ctype_digit($id)) {
                $id = (int) $id;
            }

            if (!is_int($id) || $id <= 0) {
                return '接收者ID必须为正整数';
            }

            if (isset($item['channel']) && trim((string) $item['channel']) === '') {
                return '接收渠道不能为空';
            }
        }

        return true;
    }

    protected function checkAssoc($value)
    {
        if ($value === null || $value === '') {
            return true;
        }

        if (!is_array($value)) {
            return '数据格式必须为数组';
        }

        return true;
    }
}
